13. Inserting Records, Using Debug Mode

Inserting Records and Using Debug Mode

We'll finish off creating a Hello App that says hello to our name by inserting a record into the persons table in our database, and showing the person's name on the index route.

Inserting a record

ND004 C01 L03 11.5 SQLAlchemy(App) Db.Model And Db.Create All()

Code

@app.route('/')
def index():
  person = Person.query.first()
  return 'Hello ' + person.name

Screencast cont'd (introducing debug mode)

ND004 C01 L03 11.6 SQLAlchemy(App) Db.Model And Db.Create All()

Takeaways

FLASK_DEBUG=true

will set debug mode to ON, which will automatically restart the server whenever we make changes to our application.

We can set this in-line with our flask run command,

$ FLASK_DEBUG=true flask run

or export it ahead of time in our terminal session on a separate line before we run the server,

$ export FLASK_DEBUG=true
$ flask run

Now we have everything we need to complete our Hello SQLAlchemy app. Now complete Exercise 4.

Starter Code for app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://udacitystudios@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Person(db.Model):
  __tablename__ = 'persons'
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
  return 'Hello World!'

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a